<template>
  <div class="selectionBar">
    <div
      class="selectionBaritem"
      v-for="(item, index) in list"
      :key="index"
      :class="{ active: selectType === item }"
      @click="setActive(index)"
      ref="items"
    >
      {{ item }}
    </div>
    <div class="selectionBarline" :style="selectStyle"></div>
  </div>
</template>

<script lang="ts" setup>
const props = defineProps({
  list: {
    type: Array,
    default: () => []
  },
  selectType: {
    type: String,
    default: ''
  }
})

const items = ref<HTMLElement[]>([])

const selectStyle = computed(() => {
  const idx = props.list.indexOf(props.selectType)
  if (idx === -1 || !items.value[idx]) return { opacity: 0 }

  const activeItem = items.value[idx]
  const itemRect = activeItem.getBoundingClientRect()
  const containerRect = activeItem.parentElement?.getBoundingClientRect()

  if (!containerRect) return { opacity: 0 }

  // 计算相对位置
  const left = itemRect.left - containerRect.left
  const width = itemRect.width / 2

  return {
    width: `${width}px`,
    height: '2px',
    transform: `translateX(${left + width / 2}px)`,
    opacity: 1
  }
})

const emit = defineEmits(['select', 'update:selectType'])

const setActive = (idx: number) => {
  emit('select', props.list[idx])
  emit('update:selectType', props.list[idx])
}

// 监听窗口变化重新计算位置
onMounted(() => {
  nextTick(() => {
    // 初始计算
  })

  window.addEventListener('resize', () => {
    // 强制重新计算
  })
})
</script>

<style scoped lang="scss">
.selectionBar {
  display: flex;
  position: relative;
  align-items: center;
  gap: 40px; // 根据图片中的间距调整
  font-family:
    PingFangSC,
    PingFang SC;
  font-weight: 600;
  font-size: 14px; // 根据图片中的字体大小调整
  padding: 0 20px;
}

.selectionBaritem {
  cursor: pointer;
  padding: 10px 0;
  font-size: 16px;
  transition: color 0.3s ease;
  white-space: nowrap;
  position: relative;
  z-index: 2;
}

.selectionBarline {
  position: absolute;
  bottom: 0;
  height: 2px;
  background-color: #296fff;
  transition: all 0.3s ease;
  left: 0;
}

.selectionBaritem.active {
  color: #296fff;
}
</style>
